package handle

import (
	"AcsGo/internal/domain"
	"AcsGo/internal/model"
	"strconv"
	"strings"
)

func HandleReaderInfo(str string) (string, error) {
	readerInfoRequest, err := domain.HandleReaderInfoRequest(str)
	if err != nil {
		return "", err
	}
	lg.Debugf("ReaderInfoRequest: %v", readerInfoRequest)

	db, err := model.ConnectDB()
	if err != nil {
		return "", err
	}

	reader, err := model.GetReaderByBm(db, readerInfoRequest.PatronIdentifier.Value)

	if err != nil {
		rdbm := readerInfoRequest.PatronIdentifier.Value
		rdnanme := ""
		hodlItems := ""
		queryResponse := domain.InitReaderInfoResponse(rdbm, rdnanme, hodlItems)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("读者找不到: %v", sb)
		return sb, nil
	}
	rdbm := reader.BM
	rdnanme := reader.Name
	// 读取读者借阅图书
	holdItems := ""
	ID := strconv.Itoa(reader.ID)
	pbBookRecords, err := model.GetPbBookRecord(db, ID)
	if err != nil {
		queryResponse := domain.InitReaderInfoResponse(rdbm, rdnanme, holdItems)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("success: %v", sb)
		return sb, nil
	}
	var holdItemsF strings.Builder // 使用strings.Builder进行高效拼接
	for i, pbBookRecord := range pbBookRecords {
		if i > 0 {
			holdItemsF.WriteString(",") // 只在非第一个元素前添加逗号
		}
		holdItemsF.WriteString(pbBookRecord.BARBM)
	}

	holdItems = holdItemsF.String()
	queryResponse := domain.InitReaderInfoResponse(rdbm, rdnanme, holdItems)
	sb, _ := queryResponse.StringFormat()
	lg.Debugf("success: %v", sb)
	return sb, nil
}
